package org.rency.common.utils.domain;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class SpringContextHolder implements ApplicationContextAware{

	private static ApplicationContext applicationContext;
	
	@Override
	public void setApplicationContext(ApplicationContext ctx)throws BeansException {
		applicationContext = ctx;
	}
	
	public static <T> T getBean(Class<T> requiredType){
		return applicationContext.getBean(requiredType);
	}
	
	public static Object getBean(String beanName){
		return applicationContext.getBean(beanName);
	}
	
	/**
	 * 获取继承某个父类或实现了某个接口的所有子Bean
	 * </br>Created on 2015年11月26日
	 * @param parentClass
	 * @return
	 */
	public static <T> List<T> getBeans(Class<T> parentClass){
		String[] beanNames = applicationContext.getBeanNamesForType(parentClass);
		List<String> allBeanNames = Arrays.asList(beanNames);
		List<T> result = new ArrayList<T>();
		for(String beanName : allBeanNames){
			@SuppressWarnings("unchecked")
			T bean = (T) applicationContext.getBean(beanName);
			result.add(bean);
		}
		return result;
	}

}
